package com.runa.monitor.platinterface.extend.httpSimilar.bjjn;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.newComm.AsynResult;
import com.runa.monitor.comm.dto.newComm.PanelVO;
import com.runa.monitor.comm.entity.CommPanel;
import com.runa.monitor.platinterface.mqtt.MqttUtil;
import com.runa.monitor.platinterface.platService.RepositoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@EnableScheduling
@Slf4j
@Order(999998)
public class BjjnNB implements CommandLineRunner {

    private final String panelModel = "BJJN-Panel";

    @Value("${similarNB.BJJN-Panel.enable:false}")
//    @Value("${similarNB.BJJN-Panel.enable:true}")
    private Boolean enableOfBJJN;

    @Value("${similarNB.BJJN-Panel.period:10}")
    private Long periodOfBJJN;

    //    @Value("${similarNB.BJJN-Panel.url:jdbc:sqlserver://c.bjjnrl.net,7002;DatabaseName=master}")
//    @Value("${similarNB.BJJN-Panel.url:jdbc:sqlserver://c.bjjnrl.net:7002;DatabaseName=master}")
    @Value("${similarNB.BJJN-Panel.driver:com.microsoft.sqlserver.jdbc.SQLServerDriver}")
    private String driverOfBJJN;
    @Value("${similarNB.BJJN-Panel.url:jdbc:sqlserver://c.bjjnrl.net:7002;DatabaseName=室温数据}")
    private String urlOfBJJN;
    @Value("${similarNB.BJJN-Panel.username:rn}")
    private String usernameOfBJJN;
    @Value("${similarNB.BJJN-Panel.password:rn@123!}")
    private String passwordOfBJJN;
    
    @Resource
    private RepositoryService repositoryService;

    private SqlServerConnection sqlServerConnection;

    private ConcurrentHashMap<String, String> bJRLPanelConcurrentHashMap = new ConcurrentHashMap();

    @Override
    public void run(String... args) throws Exception {
        log.info("BjjnNB CommandLineRunner Running---" + "enableOfBJRL:" + enableOfBJJN);
        if (enableOfBJJN) {
            ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleAtFixedRate(this::bjjnExecute, 0, periodOfBJJN, TimeUnit.MINUTES);
        }
    }

    private void bjjnExecute() {
        log.info("-------------http bjjnExecute Scheduled 面板信息启动-------------");
        List<CommPanel> panelList = repositoryService.getListCommPanelByNodeModel(panelModel);
        log.info("-------------http bjjnExecute Scheduled 面板信息size-------------" + panelList.size());
        if (panelList.size() > 0) {
            bjjn(panelList);
        }
//        bjjn(panelList);
    }

    private void bjjn(List<CommPanel> panelList) {
        if (sqlServerConnection == null)
            sqlServerConnection = new SqlServerConnection(driverOfBJJN, urlOfBJJN, usernameOfBJJN, passwordOfBJJN);
        ArrayList<HashMap<String, Object>> query = sqlServerConnection.query("SELECT * FROM 瑞纳创数据");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            
        }
        ArrayList<HashMap<String, Object>> query2 = sqlServerConnection.query("SELECT * FROM 瑞纳汇中数据");
        log.info(JSON.toJSONString(query));
        log.info(JSON.toJSONString(query2));

        for (CommPanel commPanel : panelList) {
            for (HashMap<String, Object> map : query) {
                if (map.get("imei").toString().equalsIgnoreCase(commPanel.getSerial())) {
//                    Date date = new Date(Long.valueOf(map.get("DNT").toString()));
                    String collectTime = map.get("DNT").toString();
                    Date date = null;
                    try {
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(collectTime);
                    } catch (ParseException e) {
                        
                    }
                    String value = map.get("t1").toString();
                    String csq = map.get("csq").toString();
//                    String num = map.get("num").toString();
                    //计量上次的采集时间
                    if (bJRLPanelConcurrentHashMap.get(commPanel.getSerial()) != null
                            && bJRLPanelConcurrentHashMap.get(commPanel.getSerial()).equalsIgnoreCase(collectTime)) {
                        continue;
                    } else {
                        bJRLPanelConcurrentHashMap.put(commPanel.getSerial(), collectTime);
                    }
                    PanelVO panelVO = new PanelVO();
                    panelVO.setReadTime(date);
                    panelVO.setSerial(commPanel.getSerial());
                    panelVO.setTemperature(Float.valueOf(value));
                    panelVO.setSignal(csq);
//                    panelVO.setCounter(Integer.valueOf(num));
                    AsynResult asynResult = new AsynResult();
                    asynResult.successSetting();
                    asynResult.setContent(Collections.singleton(panelVO));
                    asynResult.setIdentity(commPanel.getId());
                    MqttUtil.send(PanelVO.TOPIC, asynResult);
                    break;
                }
            }
            for (HashMap<String, Object> map : query2) {
                if (map.get("deviceId").toString().equalsIgnoreCase(commPanel.getSerial())) {
//                    Date date = new Date(Long.valueOf(map.get("DNT").toString()));
                    String collectTime = map.get("collectTime").toString();
                    Date date = null;
                    try {
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(collectTime);
                    } catch (ParseException e) {
                        
                    }
                    String value = map.get("temperature").toString();
                    String csq = map.get("deviceSignal").toString();
                    String humidity = map.get("humidity").toString();
                    //计量上次的采集时间
                    if (bJRLPanelConcurrentHashMap.get(commPanel.getSerial()) != null
                            && bJRLPanelConcurrentHashMap.get(commPanel.getSerial()).equalsIgnoreCase(collectTime)) {
                        continue;
                    } else {
                        bJRLPanelConcurrentHashMap.put(commPanel.getSerial(), collectTime);
                    }
                    PanelVO panelVO = new PanelVO();
                    panelVO.setReadTime(date);
                    panelVO.setSerial(commPanel.getSerial());
                    panelVO.setTemperature(Float.valueOf(value));
                    panelVO.setSignal(csq);
                    panelVO.setHumidity(Float.valueOf(humidity));
                    AsynResult asynResult = new AsynResult();
                    asynResult.successSetting();
                    asynResult.setContent(Collections.singleton(panelVO));
                    asynResult.setIdentity(commPanel.getId());
                    MqttUtil.send(PanelVO.TOPIC, asynResult);
                    break;
                }
            }
        }
    }
}
